package com.softWang.file.util.ftp;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;

import java.io.IOException;

/**
 * @author lzx
 * @Description: FTPClient线程池
 * @date 2020/8/24 15:04
 */
public class FTPClientPool {

    /**
     * ftp客户端连接池
     */
    private GenericObjectPool<FTPClient> pool;
    /**
     * ftp客户端工厂
     */
    private FTPClientFactory clientFactory;
    /**
     * 构造函数中 注入一个bean
     *
     * @param clientFactory
     */
    public FTPClientPool( FTPClientFactory clientFactory){
        this.clientFactory=clientFactory;
        pool = new GenericObjectPool<FTPClient>(clientFactory, clientFactory.getFtpPoolConfig());
        pool.setMaxTotal(100);
        pool.setMaxIdle(50);//最大并发
        pool.setMaxWaitMillis(3000);//超时等待时间
        pool.setTestOnBorrow(true);
    }

    public FTPClientFactory getClientFactory() {
        return clientFactory;
    }

    public GenericObjectPool<FTPClient> getPool() {
        return pool;
    }

    /**
     * 借  获取一个连接对象
     * @return
     * @throws Exception
     */
    public FTPClient borrowObject() throws Exception {
        FTPClient client = pool.borrowObject();
        return client ;
    }
    /**
     * 归还一个连接对象
     * @param ftpClient
     */
    public void returnObject(FTPClient ftpClient) throws IOException {
        if(ftpClient!=null){
            ftpClient.changeWorkingDirectory("/");
            pool.returnObject(ftpClient);
        }
    }

}
